function PhoneCountryCode (option){
    this.beforeshow = option.beforeshow || function(){};
    this.afterhide = option.afterhide || function(){};
    this.afterselect = option.afterselect || function(){};
    this.panel = $('#phone-country-code');
    this.countryList = this.panel.find('.country-list');
    this.countryItemList = this.countryList.find('.country-item');
    this.cancel = this.panel.find('.search .cancel');
    this.search = this.panel.find('.search input');
    this.searchResultList = this.panel.find('.search-country-list');
    this.hasLoad = false;
    this._init();
}
PhoneCountryCode.prototype.showPanel = function(){
    var _self = this;
    _self.panel.one('webkitAnimationEnd animationend',function(){
        _self.panel.removeClass('out').addClass('in').removeClass('fadein');
    });
    _self.panel.css('display','block');
    _self.beforeshow();
    _self.panel.addClass('fadein');
}
PhoneCountryCode.prototype.hidePanel = function(){
    var _self = this;
    _self.panel.one('webkitAnimationEnd animationend',function(){
        _self.panel.removeClass('in').addClass('out').removeClass('fadeout');
        _self.panel.css('display','none');
        _self.afterhide();
    });
    _self.panel.addClass('fadeout');
}
PhoneCountryCode.prototype._init = function(){
    var _self = this;
    _self.panel.on('click','.country-item',function(e){
        var code = $(this).data('code'),
            num = $(this).data('num'),
            name = $(this).find('span').html();
        _self.afterselect(code,num,name);
        _self.hidePanel();
    });
    var searchAction;
    function search(text){
        if(searchAction){
            clearTimeout(searchAction);
            searchAction = null;
            return;
        }
        searchAction = setTimeout(function(){
            _self.searchResultList.empty(); 
            _self.countryItemList.each(function(index,item){
                if($(item).find('span').html().indexOf(text) !=-1){
                    _self.searchResultList.append($(item).clone());
                }
            });
            clearTimeout(searchAction);
            searchAction = null;
        },10);
    }
    function triggerSearch(e){
        var text = $.trim($(this).val());
        if(text){
            _self.countryList.hide();
            _self.searchResultList.show();
            search(text);
        }else{
            _self.searchResultList.hide();
            _self.countryList.show();
        }
    }
    _self.search.on('input',triggerSearch);
    _self.search.on('change',triggerSearch);
    _self.cancel.on('click',function(){
        _self.hidePanel();
    });
}
window.BT = window.BT || {};
BT.PhoneCountryCode = PhoneCountryCode;
